package cn.xm.basic.rocketmq;

import cn.xm.basic.config.BussinessException;
import cn.xm.order.domain.OrderPetAcquisition;
import cn.xm.order.domain.OrderPetAcquisitionLog;
import cn.xm.order.mapper.OrderPetAcquisitionLogMapper;
import cn.xm.order.mapper.OrderPetAcquisitionMapper;
import cn.xm.pet.domain.SearchMasterMsg;
import cn.xm.pet.mapper.SearchMasterMsgMapper;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@RocketMQMessageListener(topic = "pethome_topic",consumerGroup = "pethome_consumer_group")
public class RocketmMqConsumer implements RocketMQListener<Long> {
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private OrderPetAcquisitionLogMapper orderPetAcquisitionLogMapper;

    @Override
    public void onMessage(Long id) {
        if (id == null) {
            throw new BussinessException("id出错");
        }
        // 查找订单
        OrderPetAcquisition acquisition = orderPetAcquisitionMapper.findById(id);
        if (acquisition == null) {
            throw new BussinessException("没有相应的订单");
        }
        // 订单超时未处理，就取消订单
        if (acquisition.getState() == 0) {
            acquisition.setState(-1);
            orderPetAcquisitionMapper.update(acquisition);
            // 查找对应的寻主消息
            SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(acquisition.getSearchMasterMsgId());
            if (searchMasterMsg == null) {
                throw new BussinessException("没有相应寻主消息");
            }
            searchMasterMsg.setState(-1);
            searchMasterMsg.setShopId(null);
            searchMasterMsgMapper.update(searchMasterMsg);
            // 添加日志
            OrderPetAcquisitionLog orderPetAcquisitionLog = new OrderPetAcquisitionLog();
            orderPetAcquisitionLog.setAuditTime(new Date());
            orderPetAcquisitionLog.setAcquisitionId(acquisition.getId());
            orderPetAcquisitionLogMapper.update(orderPetAcquisitionLog);

        }

    }
}
